﻿using ORM.Applicaiton;
using ORM.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ORM.Parser.Design
{
    public class DeleteStatement : BaseStatement
    {
        public string Expression { set; get; }
        public DataTable DeleteRow { set; get; }
        public override void Parse(string SQLText)
        {
            base.Parse(SQLText);
            DBUtil dbutil = new DBUtil();
            int fromindex = this.SQLText.IndexOf("from\n");
            int whereindex = this.SQLText.IndexOf("where\n");
            this.TableName = this.SQLText.Substring(fromindex + 6, whereindex - fromindex - 6).Trim();
            this.Expression = this.SQLText.Substring(whereindex + 6, this.SQLText.Length - whereindex - 6).Trim();
            DeleteRow = dbutil.FindView(string.Format("select * from {0} where {1}", TableName, Expression), ConnectStringName);
        }

        public override List<string> GetRollBackSQL()
        {
           
            foreach (DataRow row in DeleteRow.Rows)
            {
                StringBuilder rollbackbuilder = new StringBuilder();
                rollbackbuilder.AppendFormat("insert into {0} (", TableName);
                foreach (DataColumn item in DeleteRow.Columns)
                {
                    rollbackbuilder.Append(item.ColumnName);
                    if (DeleteRow.Columns.IndexOf(item) != DeleteRow.Columns.Count - 1)
                    {
                        rollbackbuilder.Append(",");
                    }

                }
                rollbackbuilder.Append(") values ");
                rollbackbuilder.Append("(");
                foreach (DataColumn column in DeleteRow.Columns)
                {
                    string columnvalue = Convert.IsDBNull(row[column.ColumnName]) ? string.Empty : Convert.ToString(row[column.ColumnName]);
                    rollbackbuilder.Append("'" + columnvalue + "'");
                    if (DeleteRow.Columns.IndexOf(column) != DeleteRow.Columns.Count - 1)
                    {
                        rollbackbuilder.Append(",");
                    }
                }
                rollbackbuilder.Append(")");
                this.RollBackSQLTextList.Add(rollbackbuilder.ToString());
            }
            return base.GetRollBackSQL();

        }
    }
}
